package com.zyw.apple;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author zhangyw
 * @version 17/3/9 21:31
 */
@Component
public class AppleDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int insert(Apple apple) {
        return jdbcTemplate.update("INSERT INTO APPLE(`number`,`weight`) VALUES (?,?)", apple.getNumber(), apple.getWeight());
    }

    public List<Apple> findAll() {

        if (true)
            throw new IllegalArgumentException();

        return jdbcTemplate.query("SELECT * FROM APPLE", new RowMapper<Apple>() {
            /**
             * Implementations must implement this method to map each row of data
             * in the ResultSet. This method should not call {@code next()} on
             * the ResultSet; it is only supposed to map values of the current row.
             *
             * @param rs     the ResultSet to map (pre-initialized for the current row)
             * @param rowNum the number of the current row
             * @return the result object for the current row
             * @throws SQLException if a SQLException is encountered getting
             *                      column values (that is, there's no need to catch SQLException)
             */
            public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {
                Apple apple = new Apple();
                apple.setId(rs.getInt("id"));
                apple.setNumber(rs.getInt("number"));
                apple.setWeight(rs.getDouble("weight"));
                return apple;
            }
        });
    }
}
